<template>
  <div id="login">
    <div class="bg"></div>
    <div class="wrap">
      <header>Easy Contacts</header>
      <div class="form-login">
        <el-form 
          label-position="right" 
          label-width="80px" 
          :model="formLogin"
          :rules="rules"
          ref="formLogin">
          <!-- $refs 只在组件渲染完成后才填充，并且它是非响应式的。它仅仅作为一个直接访问子组件的应急方案——应当避免在模版或计算属性中使用 $refs 。 -->
          <el-form-item label="账号" prop="name">
            <el-input v-model="formLogin.name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formLogin.password" type="password"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="login">登录</el-button>
              <el-button @click="resetForm">取消</el-button>
          </el-form-item>
          <el-form-item>
            <router-link to="/register">
              <el-button type="">没有账号，立即注册<i class="el-icon-arrow-right el-icon--right"></i></el-button>
            </router-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">
  // 引入vuex /src/helper.js中的辅助函数，
  // 将actions中的方法直接转为组件中的方法
  import {mapActions} from 'vuex'
  const qs = require('qs')
  export default {
    data(){
      let checkUserName = (rule,value,cb)=>{
        if(!value){
          return cb(new Error('账户不能为空!'))
        }else{
          cb(); // 将判断传递给后面
        }

      }
      let checkPassword = (rule,value,cb)=>{
        if(!value){
          return cb(new Error('密码不能为空!'))
         }else{
          cb();
         }
      }
      return{
        formLogin:{
          name: '',
          password: '',
          checkPassword: ''
        },
        rules:{
          name:[
            {validator:checkUserName,trigger: 'blur'}
          ],
          password:[
            {validator:checkPassword,trigger: 'blur'}
          ]
        }
      }
    },
    methods:{
      ...mapActions(['userLogin']),
      // 向登录接口发起请求
      login(){
        let user = this.formLogin;
        let formData = {
          name: user.name,
          password: user.password
        };
        // 表单验证
        this.$refs['formLogin'].validate((valid) => {
          if (valid) {
            // 通过验证之后才请求登录接口
            this.$http.post('http://119.29.151.195:3000/api/token/login', qs.stringify(formData))
                .then(res => {
                    if (res.data.success) {
                      this.userLogin(res.data);
                      this.$message.success(`${res.data.message}`)
                      // 登录成功 跳转至首页
                      this.$router.push({name:'home'}) 
                    }else{
                      this.$message.error(`${res.data.message}`);
                      return false;
                    }
                })
                .catch(err => {
                    this.$message.error(`${err.message}`, 'ERROR!')
                })
          } else {
            this.$message.error('表单验证失败!')
            return false;
          }
        });
      },
      // 表单重置
      resetForm(){
        this.$refs['formLogin'].resetFields()
      }
    }
  }
</script>
<style lang="scss">
  html, body {
    height: 100% !important;
  }
  #login {
    .bg {
      width: 100%;
      height: 100%;
      background: url(https://oc1gyfe6q.qnssl.com/17-5-18/51286320-file_1495096954560_177f8.jpg) no-repeat;
      -webkit-filter: blur(2px); /* Chrome, Opera */
      -moz-filter: blur(2px);
      -ms-filter: blur(2px);    
          filter: blur(2px);
      background-size: 100% 100%;
    }
    margin: 0 auto;
    width: 100%;
    height: 100%;
    overflow: hidden;
    min-height: 585px;
    position: relative; 
    header {
      text-align: center;
      font: 40px/150% 'Microsoft YaHei','Hiragino Sans GB',Arial,sans-serif;
      color: #45484d;
      width: 400px;
      height: 60px;
    }
    .wrap {
      width: 400px;
      height: 300px;
      background: rgba(197, 196, 231, 0.81);
      border: 1px solid #ddd;
      border-radius: 5px;
      box-shadow: 1px 1px 1px 1px gainsboro;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
      .form-login { 
        display: flex;
        flex-direction: column;
        padding: 20px;
      }
    }
  }
</style>